import React from 'react';
import { Card, Row, Col, Statistic, Typography, Tag, Space, Progress } from 'antd';
import {
  BugOutlined,
  WarningOutlined,
  InfoCircleOutlined,
  FileTextOutlined,
  RobotOutlined,
  SettingOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons';
import { ProblemStatistics } from '../../types/taskDetail';
import { TaskScanResults } from '../../services/api';
import './ScanResults.css';

const { Text, Title } = Typography;

interface ProblemOverviewProps {
  results: TaskScanResults | null;
  loading?: boolean;
}

const ProblemOverview: React.FC<ProblemOverviewProps> = ({ results, loading }) => {
  
  // 计算统计数据
  const calculateStatistics = (): ProblemStatistics => {
    if (!results || !results.issues) {
      return {
        total: 0,
        high: 0,
        medium: 0,
        low: 0,
        info: 0,
        aiAnalyzed: 0,
        ruleAnalyzed: 0,
        categories: {
          syntax: 0,
          function: 0,
          datatype: 0,
          performance: 0,
          compatibility: 0
        },
        sqlStatements: {
          totalStatements: results?.sqlStatements || 0,
          problemStatements: 0,
          problemRate: 0
        }
      };
    }

    const issues = results.issues;
    const stats: ProblemStatistics = {
      total: issues.length,
      high: issues.filter(i => i.severity === 'HIGH').length,
      medium: issues.filter(i => i.severity === 'MEDIUM').length,
      low: issues.filter(i => i.severity === 'LOW').length,
      info: issues.filter(i => i.severity === 'INFO').length,
      aiAnalyzed: issues.filter(i => {
        // 优先检查metadata中的分析引擎信息
        if (i.metadata?.analysisEngine === 'LLM_BASED') return true;
        if (i.metadata?.analysisEngine === 'RULE_BASED') return false;
        if (i.metadata?.analysisSource === 'LLM') return true;
        if (i.metadata?.analysisSource === 'RULE') return false;
        // 备用：检查ruleId模式
        return i.ruleId?.startsWith('AI_') || i.ruleId?.includes('LLM') || false;
      }).length,
      ruleAnalyzed: issues.filter(i => {
        // 优先检查metadata中的分析引擎信息
        if (i.metadata?.analysisEngine === 'RULE_BASED') return true;
        if (i.metadata?.analysisEngine === 'LLM_BASED') return false;
        if (i.metadata?.analysisSource === 'RULE') return true;
        if (i.metadata?.analysisSource === 'LLM') return false;
        // 备用：检查ruleId模式
        return !(i.ruleId?.startsWith('AI_') || i.ruleId?.includes('LLM'));
      }).length,
      categories: {
        syntax: issues.filter(i => i.issueType?.toLowerCase().includes('syntax')).length,
        function: issues.filter(i => i.issueType?.toLowerCase().includes('function')).length,
        datatype: issues.filter(i => i.issueType?.toLowerCase().includes('datatype')).length,
        performance: issues.filter(i => i.issueType?.toLowerCase().includes('performance')).length,
        compatibility: issues.filter(i => i.issueType?.toLowerCase().includes('compatibility')).length,
      },
      sqlStatements: {
        totalStatements: results.sqlStatements || 0,
        problemStatements: results.problemSqlStatements || 0,  // 使用后端返回的字段
        problemRate: results.sqlStatements ? ((results.problemSqlStatements || 0) / results.sqlStatements) * 100 : 0
      }
    };

    return stats;
  };

  const stats = calculateStatistics();

  // 获取严重程度配置
  const getSeverityConfig = (severity: string, count: number) => {
    const configs = {
      HIGH: {
        color: '#ff4d4f',
        bgColor: 'linear-gradient(135deg, #fff1f0 0%, #ffccc7 100%)',
        borderColor: '#ffccc7',
        icon: <BugOutlined />,
        text: '高危问题',
        textColor: '#ff4d4f'
      },
      MEDIUM: {
        color: '#faad14', 
        bgColor: 'linear-gradient(135deg, #fffbe6 0%, #ffe7ba 100%)',
        borderColor: '#ffe7ba',
        icon: <WarningOutlined />,
        text: '中危问题',
        textColor: '#faad14'
      },
      LOW: {
        color: '#1890ff',
        bgColor: 'linear-gradient(135deg, #e6f7ff 0%, #bae7ff 100%)',
        borderColor: '#bae7ff',
        icon: <InfoCircleOutlined />,
        text: '低危问题', 
        textColor: '#1890ff'
      },
      TOTAL: {
        color: '#722ed1',
        bgColor: 'linear-gradient(135deg, #f9f0ff 0%, #efdbff 100%)',
        borderColor: '#efdbff',
        icon: <FileTextOutlined />,
        text: '总问题数',
        textColor: '#722ed1'
      }
    };
    
    return configs[severity as keyof typeof configs];
  };

  // 渲染严重程度卡片
  const renderSeverityCard = (severity: string, count: number) => {
    const config = getSeverityConfig(severity, count);
    if (!config) return null;

    return (
      <Card 
        hoverable 
        className="severity-card"
        style={{ 
          borderRadius: 12, 
          border: `1px solid ${config.borderColor}`, 
          background: config.bgColor,
          height: '100%'
        }} 
        bodyStyle={{ padding: 16, textAlign: 'center' }}
      >
        <div className="severity-icon" style={{ color: config.color, fontSize: 28, marginBottom: 12 }}>
          {config.icon}
        </div>
        <Statistic
          title={config.text}
          value={count}
          valueStyle={{ 
            color: config.textColor, 
            fontSize: 24, 
            fontWeight: 'bold' 
          }}
        />
        {severity !== 'TOTAL' && (
          <div style={{ marginTop: 8 }}>
            <Text type="secondary" style={{ fontSize: 11 }}>
              占比 {stats.total > 0 ? ((count / stats.total) * 100).toFixed(1) : 0}%
            </Text>
          </div>
        )}
      </Card>
    );
  };

  return (
    <div className="problem-overview">
      <div className="overview-header">
        <Title level={4} style={{ margin: 0, color: '#1890ff' }}>
          扫描结果概览
        </Title>
        <Space>
          {stats.total > 0 ? (
            <Tag color={stats.high > 0 ? 'error' : stats.medium > 0 ? 'warning' : 'success'}>
              {stats.high > 0 ? '发现高危问题' : stats.medium > 0 ? '发现中危问题' : '扫描正常'}
            </Tag>
          ) : (
            <Tag color="default">暂无问题</Tag>
          )}
        </Space>
      </div>

      {/* 问题严重程度统计 */}
      <div className="severity-statistics">
        <Row gutter={[16, 16]}>
          <Col xs={12} sm={6}>
            {renderSeverityCard('HIGH', stats.high)}
          </Col>
          <Col xs={12} sm={6}>
            {renderSeverityCard('MEDIUM', stats.medium)}
          </Col>
          <Col xs={12} sm={6}>
            {renderSeverityCard('LOW', stats.low)}
          </Col>
          <Col xs={12} sm={6}>
            {renderSeverityCard('TOTAL', stats.total)}
          </Col>
        </Row>
      </div>

      {/* 基础统计信息 */}
      <div className="basic-statistics">
        <Row gutter={[16, 16]}>
          <Col xs={24} sm={8}>
            <Card
              title={
                <Space>
                  <SettingOutlined style={{ color: '#1890ff' }} />
                  <span>分析来源统计</span>
                </Space>
              }
              className="analysis-source-card"
              size="small"
            >
              <div className="stat-row">
                <div className="stat-item">
                  <div className="stat-icon">
                    <RobotOutlined style={{ color: '#722ed1', fontSize: 16 }} />
                  </div>
                  <div className="stat-content">
                    <div className="stat-value">{stats.aiAnalyzed}</div>
                    <div className="stat-label">AI分析</div>
                  </div>
                </div>
                <div className="stat-item">
                  <div className="stat-icon">
                    <SettingOutlined style={{ color: '#1890ff', fontSize: 16 }} />
                  </div>
                  <div className="stat-content">
                    <div className="stat-value">{stats.ruleAnalyzed}</div>
                    <div className="stat-label">规则分析</div>
                  </div>
                </div>
              </div>
            </Card>
          </Col>

          <Col xs={24} sm={8}>
            <Card
              title={
                <Space>
                  <ExclamationCircleOutlined style={{ color: '#fa8c16' }} />
                  <span>问题类型统计</span>
                </Space>
              }
              className="problem-type-card"
              size="small"
            >
              <div className="problem-types">
                <div className="problem-type-item">
                  <Tag color="red">语法</Tag>
                  <Text>{stats.categories.syntax}</Text>
                </div>
                <div className="problem-type-item">
                  <Tag color="orange">函数</Tag>
                  <Text>{stats.categories.function}</Text>
                </div>
                <div className="problem-type-item">
                  <Tag color="blue">类型</Tag>
                  <Text>{stats.categories.datatype}</Text>
                </div>
                <div className="problem-type-item">
                  <Tag color="green">性能</Tag>
                  <Text>{stats.categories.performance}</Text>
                </div>
                <div className="problem-type-item">
                  <Tag color="purple">兼容性</Tag>
                  <Text>{stats.categories.compatibility}</Text>
                </div>
              </div>
            </Card>
          </Col>

          <Col xs={24} sm={8}>
            <Card
              title={
                <Space>
                  <FileTextOutlined style={{ color: '#52c41a' }} />
                  <span>SQL语句统计</span>
                </Space>
              }
              className="sql-stats-card"
              size="small"
            >
              <div className="sql-statistics">
                <div className="sql-stat-item">
                  <Text type="secondary">总SQL语句</Text>
                  <div className="sql-stat-value">{stats.sqlStatements.totalStatements}</div>
                </div>
                <div className="sql-stat-item">
                  <Text type="secondary">有问题SQL</Text>
                  <div className="sql-stat-value problem">{stats.sqlStatements.problemStatements}</div>
                </div>
                <div className="sql-stat-item">
                  <Text type="secondary">问题率</Text>
                  <div className="sql-stat-progress">
                    <Progress 
                      percent={Math.round(stats.sqlStatements.problemRate)} 
                      size="small"
                      strokeColor={
                        stats.sqlStatements.problemRate > 20 ? '#ff4d4f' :
                        stats.sqlStatements.problemRate > 10 ? '#faad14' : '#52c41a'
                      }
                      format={(percent) => `${percent}%`}
                    />
                  </div>
                </div>
              </div>
            </Card>
          </Col>
        </Row>
      </div>
    </div>
  );
};

export default ProblemOverview;